using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO;
using Ltf.Remoting.TeamFoundation;
using Ltf.MonitorLizard.Forms;
using Ltf.Remoting.RemoteEvents;
using Ltf.Remoting.Server;
using Ltf.Remoting.Operations;

namespace Ltf.MonitorLizard
{
	[FormType(FormTypes.CreateNewWorkSpace)]
	public partial class TFCreateWorkspace : Form
	{
		private Dictionary<string, TeamProject> teamProjects;
		private string selectedProjectPath = string.Empty;
		private Ltf.MonitorLizard.Helpers.FileIcons fileIcons;
		private TFServerConnection connection;


		public TFCreateWorkspace(string[] paths, LizardEventArgs args)
		{
			connection = ServerConnections.GetConnectionForPath(paths[0]);
			workspacePath = paths[0];
			InitializeComponent();
			txtComputerName.Text = Environment.MachineName;
			txtUsername.Text = connection.Settings.GetTFSUserName();
			txtLocalPath.Text = workspacePath;
			fileIcons = new Ltf.MonitorLizard.Helpers.FileIcons(imlTreeImages);
			LoadProjectsCombo();
			tvwProject.AfterSelect += new TreeViewEventHandler(tvwProject_AfterSelect);
			tvwProject.BeforeSelect += new TreeViewCancelEventHandler(tvwProject_BeforeSelect);
			tvwProject.BeforeExpand += new TreeViewCancelEventHandler(tvwProject_BeforeSelect);
		}


		private string projectPath = string.Empty;

		private string workspacePath = string.Empty;

		public string WorkspacePath
		{
			get { return WorkspacePath; }
			set { WorkspacePath = value; }
		}

		private void LoadProjectsCombo()
		{
			VersionControlServer vcServer = connection.VersionControlServer;

			TeamProject[] projects=vcServer.GetAllTeamProjects(true);

			cmbProjects.Items.Clear();
			teamProjects = new Dictionary<string, TeamProject>();
			foreach (TeamProject tp in projects)
			{
				cmbProjects.Items.Add(tp.Name);
				teamProjects.Add(tp.Name, tp);
			}
			if (cmbProjects.SelectedIndex==-1)
				cmbProjects.SelectedIndex = 0;
		}

		private void cmbProjects_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (teamProjects!=null && teamProjects.ContainsKey(cmbProjects.SelectedItem.ToString()))
			{
				LoadProjectHierarchy(teamProjects[cmbProjects.SelectedItem.ToString()]);
			}
		}

		//private void LoadProjectHierarchy(TeamProject teamProject)
		//{
		//  tvwProject.Nodes.Clear();
		//  TreeNode tn = tvwProject.Nodes.Add(teamProject.Name);
		//  tn.Tag = teamProject.ServerItem;
		//  tn.ImageIndex = 0;
		//  tn.SelectedImageIndex = 0;
		//  RecurseLoadItems(tn, teamProject.ServerItem, teamProject.VersionControlServer);
		//  if (tvwProject.SelectedNode == null && tvwProject.Nodes.Count > 0)
		//    tvwProject.SelectedNode = tvwProject.Nodes[0];
		//}

		//private void RecurseLoadItems(TreeNode treeNode, string serverItem, VersionControlServer vcServer)
		//{
		//  ItemSet items = vcServer.GetItems(serverItem+"/*");
		//  foreach (Item item in items.Items)
		//  {
		//    if (item.ItemType == ItemType.Folder)
		//    {
		//      TreeNode tn = treeNode.Nodes.Add(Path.GetFileName(item.ServerItem));
		//      tn.ImageIndex = 0;
		//      tn.SelectedImageIndex = 0;
		//      tn.Tag = item.ServerItem;
		//      if (item.ServerItem == projectPath)
		//      {
		//        tvwProject.SelectedNode = tn;
		//      }
		//      RecurseLoadItems(tn, item.ServerItem, vcServer);
		//    }
		//  }
		//}

		private VersionControlServer versionControlServer;

		private void LoadProjectHierarchy(TeamProject teamProject)
		{
			using (HourGlass hg = new HourGlass(this))
			{
				tvwProject.Nodes.Clear();
				TreeNode tn = tvwProject.Nodes.Add(teamProject.Name);
				tn.Tag = "..." + teamProject.ServerItem;
				tn.ImageIndex = 0;
				tn.SelectedImageIndex = 0;
				versionControlServer = teamProject.VersionControlServer;
				tvwProject.SelectedNode = null;
				LoadItems(tn, teamProject.ServerItem);
			}
		}

		bool loading = false;
		private void LoadItems(TreeNode treeNode, string serverItem)
		{
			if (loading)
				return;
			loading = true;
			if (treeNode.Nodes.Count == 1 && treeNode.Nodes[0].Tag.ToString() == "***dummy")
				treeNode.Nodes.RemoveAt(0);

			ItemSet items = versionControlServer.GetItems(serverItem, VersionSpec.Latest, RecursionType.OneLevel, DeletedState.Any, ItemType.Folder);
			foreach (Item item in items.Items)
			{
				if (item.ServerItem != serverItem && (item.DeletionId == 0))
				{
					//if (item.ItemType == ItemType.Folder)
					//{
					TreeNode tn = treeNode.Nodes.Add(Path.GetFileName(item.ServerItem));
					if (item.ItemType == ItemType.Folder)
					{
						tn.ImageKey = "$folder";
						tn.Tag = "..." + item.ServerItem;
						TreeNode dummy = tn.Nodes.Add("Loading...");
						dummy.Tag = "***dummy";
					}
					else
					{
						tn.ImageKey = fileIcons.LoadIconForFileExtension(Path.GetExtension(item.ServerItem));
						tn.Tag = item.ServerItem;
					}
					if (item.DeletionId != 0 || treeNode.ForeColor == System.Drawing.Color.Tomato)
					{
						tn.ForeColor = System.Drawing.Color.Tomato;
						tn.NodeFont = new System.Drawing.Font(tvwProject.Font, FontStyle.Strikeout);
					}
					tn.SelectedImageKey = tn.ImageKey;
					if (projectPath.StartsWith(item.ServerItem) && projectPath != item.ServerItem)
					{
						loading = false;
						LoadItems(tn, item.ServerItem);
						loading = true;
						if (tvwProject.SelectedNode == null)
							tvwProject.SelectedNode = tn;
					}
					else if (projectPath == item.ServerItem)
					{
						tvwProject.SelectedNode = tn;
					}
				}
			}
			loading = false;
		}


		private void btnOkay_Click(object sender, EventArgs e)
		{
			if (txtWorkspaceName.Text==string.Empty)
			{
				MessageBox.Show("You must enter a valid workspace name.","Invalid Name",MessageBoxButtons.OK,
					MessageBoxIcon.Error);
				return;
			}
			projectPath = selectedProjectPath;
			try
			{
				VersionControlServer vcs = connection.VersionControlServer;
				WorkingFolder[] mappings = new WorkingFolder[] { new WorkingFolder(projectPath, workspacePath) };
				vcs.CreateWorkspace(txtWorkspaceName.Text, txtUsername.Text, txtComment.Text, mappings, txtComputerName.Text);
			}
			catch (Exception ex)
			{
				string msg = string.Format("The attempt to create the workspace '{0}' failed with the exception :\r\n{1}",
					txtWorkspaceName.Text, ex.Message);
				MessageBox.Show(msg, "Create Workspace Failed", MessageBoxButtons.OK,
					MessageBoxIcon.Error);
				return;
			}
			string msg2 = string.Format("Creation of the workspace '{0}' was successfull. Do you wish to download the latest server versions for this workspace?",
				txtWorkspaceName.Text);
			DialogResult dr = MessageBox.Show(msg2, "Create Workspace Successfull", MessageBoxButtons.YesNo,
				MessageBoxIcon.Information);
			if (dr == DialogResult.Yes)
			{
				using (new BusyIndicator("LizardTF Get", "Getting latest versions...", false))
				{
					WorkspaceOperators wso = new WorkspaceOperators(connection, connection.GetWorkspace(workspacePath));
					GetStatus gs = wso.Get(new string[] { workspacePath }, LatestVersionSpec.Latest, RecursionType.Full, false, false);
					string results = string.Format("Updates:{0}\r\nWarnings:{1}\r\nConflicts:{2}\r\n",
						gs.NumOperations - gs.NumConflicts - gs.NumWarnings, gs.NumWarnings, gs.NumConflicts);
				}

			}

			this.Close();
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			Close();
		}

		void tvwProject_BeforeSelect(object sender, TreeViewCancelEventArgs e)
		{
			if (e.Node.Tag.ToString().StartsWith("...") && e.Node.Nodes.Count == 1
				&& e.Node.Nodes[0].Text == "Loading...")
			{
				LoadItems(e.Node, e.Node.Tag.ToString().Substring(3));
				if (!loading)
					e.Node.Expand();
			}
		}

		void tvwProject_AfterSelect(object sender, TreeViewEventArgs e)
		{
			if (tvwProject.SelectedNode != null)
			{
				selectedProjectPath = tvwProject.SelectedNode.Tag.ToString().Replace("...", "");
				//ignoreVersionChange = true;
				//LizardFileAccess.LoadVersions(cmbVersion, selectedProjectPath, projectVersion);
				//historySelector.Path = selectedProjectPath;
				//ignoreVersionChange = false;
			}
		}

	
	}
}